package ext.tianma.part.copybom;

import java.rmi.RemoteException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

import wt.fc.ObjectReference;
import wt.fc.PersistenceServerHelper;
import wt.fc.WTObject;
import wt.fc.collections.WTCollection;
import wt.lifecycle.LifeCycleManaged;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartSubstituteLink;
import wt.part.WTPartUsageLink;
import wt.session.SessionHelper;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.wip.WorkInProgressHelper;
import wt.vc.wip.Workable;

import com.ptc.core.components.forms.DefaultObjectFormProcessor;
import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;
import com.ptc.core.components.forms.FormResultAction;
import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;
import com.ptc.netmarkets.model.NmOid;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;

/**
 * 复制零部件结构，包括替换件
 * @author zengchen
 *
 */
public class CopyBomProcessor extends DefaultObjectFormProcessor {

	@SuppressWarnings({ "deprecation", "rawtypes" })
	public FormResult doOperation(NmCommandBean nmcommandbean, List list)
			throws WTException {
		NmOid nmoid = nmcommandbean.getActionOid();
		WTPart wtpart = (WTPart) nmoid.getRefObject();
		Locale locale = SessionHelper.getLocale();
		FormResult formresult = new FormResult();
		String targetPartNumber = (String) nmcommandbean.getText().get(
				"partNumber");

		if (wtpart != null) {
			String viewName = wtpart.getViewName();
			System.out.println("view:" + viewName);
			// 判断目标零部件是否存在，是否被检出，生命周期状态是否是新品或量产发布
			String errorMessage = checkTargetPart(targetPartNumber, viewName);
			System.out.println("errorMessage:" + errorMessage);
			if (!"".equals(errorMessage)) {
				formresult.setStatus(FormProcessingStatus.FAILURE);
				String js = "alert(\"" + errorMessage + "\");window.close();";
				formresult.setJavascript(js);
				formresult.setNextAction(FormResultAction.JAVASCRIPT);
			} else {
				
				WTPart targetPart = CoreUtil.getWTPartByNumberAndView(
						targetPartNumber, viewName);
				//复制BOM结构
				copyWTPartUsageLink(wtpart, targetPart);
				
				FeedbackMessage feedbackmessage = new FeedbackMessage(
						FeedbackType.SUCCESS, locale, "复制结构成功！",
						null, new String[] { "" });
				formresult.addFeedbackMessage(feedbackmessage);
				formresult.setStatus(FormProcessingStatus.SUCCESS);
			}
		}

		return formresult;
	}

	/**
	 * 复制第一层WTPartUsageLink
	 * @param wtpart 当前零部件
	 * @param targetPart BOM的源零部件
	 */
	@SuppressWarnings("unchecked")
	private void copyWTPartUsageLink(WTPart wtpart, WTPart targetPart) {
		try {
			Vector<WTPartUsageLink> partlinks = CoreUtil.getPartUsageLinks(targetPart);

			for (WTPartUsageLink wtPartUsageLink : partlinks) {
				
				WTPartMaster sonPartMaster = wtPartUsageLink.getUses();
				WTPart childPart = CoreUtil.getWTPartByMasterAndView(sonPartMaster, targetPart.getViewName());
				if(childPart != null){
					String softTypeInternal = getSoftTypeInternal(childPart);
					System.out.println("softTypeInternal === " + softTypeInternal);
					if(! softTypeInternal.equals("TwoLevelMaterial")){
						WTPartUsageLink newlink = WTPartUsageLink.newWTPartUsageLink(wtpart, sonPartMaster);

						//行号
						newlink.setLineNumber(wtPartUsageLink.getLineNumber());
						
						//单位和数量
						newlink.setQuantity(wtPartUsageLink.getQuantity());
						
						//产出率
						String chanchulv = (String)IBAUtil.getIBAValue(wtPartUsageLink, "Yield");
						//BOM说明
						String bomMark=(String) IBAUtil.getIBAValue(wtPartUsageLink, "BomNote");
						
						PersistenceServerHelper.manager.insert(newlink);
						//复制替换件
						copySubstituteLink(wtPartUsageLink, newlink);
						
						System.out.println(chanchulv + "  |  " + bomMark);
						Hashtable<String, String> table = new Hashtable<String, String>();
						if(chanchulv != null){
							table.put("Yield", chanchulv);
						}
						if(bomMark != null){
							table.put("BomNote", bomMark);
						}
						IBAUtil.setSoftTypeIBAValues(newlink, table);
					}
				}
			}
		} catch (WTException e) {
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
			
	}

	/**
	 * 复制替代关系
	 * @param wtPartUsageLink 源link
	 * @param newlink 新建的link
	 */
	@SuppressWarnings("rawtypes")
	private void copySubstituteLink(WTPartUsageLink wtPartUsageLink,
			WTPartUsageLink newlink) {
		//获取usageLink上的所有特定替代关系
		try {
			WTCollection wtcol = WTPartHelper.service.getSubstituteLinks(wtPartUsageLink);
			if(wtcol != null){
				System.out.println("link 个数：" + wtcol.size());
				Iterator ite = wtcol.iterator() ;
				while( ite.hasNext()){
					Object obj = ite.next();
					if( obj != null && obj instanceof ObjectReference){
						ObjectReference objRef = ( ObjectReference )obj;
						Object tempObj = objRef.getObject();
						if(tempObj != null && tempObj instanceof WTPartSubstituteLink){
							WTPartSubstituteLink oldSubstituteLink = (WTPartSubstituteLink) tempObj;
							//创建WTPartSubstituteLink
							WTPartSubstituteLink newSubstituteLink = WTPartSubstituteLink.newWTPartSubstituteLink(newlink , oldSubstituteLink.getSubstitutes());
							newSubstituteLink.setQuantity(oldSubstituteLink.getQuantity());
							PersistenceServerHelper.manager.insert(newSubstituteLink);
						}
					}
				}
			}
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}

	/**
	 * 判断目标零部件是否存在，是否被检出，生命周期状态是否是新品或量产发布
	 * 
	 * @param targetPartNumber
	 *            零部件编号
	 * @param viewName
	 *            零部件视图
	 * @return 判断结果
	 */
	private String checkTargetPart(String targetPartNumber, String viewName) {
		try {
			WTPart targetPart = CoreUtil.getWTPartByNumberAndView(
					targetPartNumber, viewName);
			

			if (targetPart == null) {
				return "料号错误或该料号没有对应视图";
			} else {
				String targetPartView = targetPart.getViewName();
				if(!viewName.equalsIgnoreCase(targetPartView)){
					return "料号错误或该料号没有对应视图";
				}
			}

			Workable workble = (Workable) targetPart;
			if (WorkInProgressHelper.isCheckedOut(workble)) {
				return "该物料已被检出";
			}

			LifeCycleManaged lcm = (LifeCycleManaged) targetPart;
			System.out.println("00:"+lcm.getLifeCycleState());
			if (!"NewProduct".equals(lcm.getLifeCycleState().toString())
					&& !"MassProductionRelease".equals(lcm.getLifeCycleState().toString())
					&& !"TrialProduction".equals(lcm.getLifeCycleState().toString())
					&& !"CustomerSample".equals(lcm.getLifeCycleState().toString())
					&& !"RiskOrder".equals(lcm.getLifeCycleState().toString())) {
				return "该物料状态不符合“新品”或“量产发布”或“试产”或“小批量”或“风险批量”";
			}

		} catch (WTException e) {
			e.printStackTrace();
		}

		return "";
	}
	
	/**
	 * 获取对象的软类型
	 * 
	 * @param obj
	 * @return
	 */
	public  String getSoftTypeInternal( WTObject obj) {
		String internalName = "";
		
		if(obj!=null) {
			try {
				internalName=ClientTypedUtility.getTypeIdentifier(obj).getTypename() ;
				
				if( internalName != null ){
					int startIndex = internalName.lastIndexOf(".") + 1 ;
					internalName = internalName.substring( startIndex ) ;

				}
			} catch(WTException e) {
				e.printStackTrace() ;
			}
		}
		return internalName; 
	}
}
